const storage = require('../../utils/storage.js');
const api = require('../../utils/api.js');
const imageUtil = require('../../utils/image.js');
const permission = require('../../utils/permission.js'); // 🎯 引入权限工具
const level = require('../../utils/level.js'); // 🎯 引入等级工具

Page({
  data: {
    statusBarHeight: 0,
    currentUserId: null, // 当前登录用户的ID
    targetUserId: null, // 目标用户ID（要查看的用户）
    isMyself: false, // 是否查看自己的信息
    userInfo: {
      nickname: '用户',
      avatar: '/images/icons/avatar.png',
      photos: [], // 用户相册
      currentPhotoIndex: 0,
      levelName: '追随者',
      fans: 0,
      likes: 0,
      signature: '这个人很懒，什么都没留下',
      hobbies: [ // 🔥 爱好列表（带选中状态）
        { name: '吃', isSelected: false },
        { name: '喝', isSelected: false },
        { name: '玩', isSelected: false },
        { name: '乐', isSelected: false },
        { name: '购', isSelected: false }
      ],
      frequentPlaces: '未知'
    },
    activities: [], // 用户的活动列表
    loading: true
  },

  /**
   * 🎯 数字格式化函数
   */
  formatNumber(number) {
    if (number >= 100000) {
      const result = number / 10000.0;
      let formatted = result.toFixed(1);
      if (formatted.endsWith('.0')) {
        formatted = formatted.substring(0, formatted.length - 2);
      }
      return formatted + 'w';
    } else if (number >= 10000) {
      const result = number / 10000.0;
      let formatted = result.toFixed(2);
      formatted = formatted.replace(/\.?0+$/, '');
      return formatted + 'w';
    } else if (number >= 1000) {
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    } else {
      return number.toString();
    }
  },

  onLoad(options) {
    console.log('🎯 =============== 用户主页加载 ===============');
    console.log('📦 接收参数:', options);

    const windowInfo = wx.getWindowInfo();
    
    // 获取当前登录用户信息
    const currentUser = storage.getUserInfo();
    const currentUserId = currentUser ? currentUser.userid : null;
    
    // 获取目标用户ID（要查看的用户）
    const targetUserId = options.userId ? parseInt(options.userId) : currentUserId;
    
    // 判断是否查看自己的信息
    const isMyself = !options.userId || (targetUserId === currentUserId);
    
    console.log('👤 当前登录用户ID:', currentUserId);
    console.log('🎯 目标用户ID:', targetUserId);
    console.log('🔍 是否查看自己:', isMyself);
    
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight,
      currentUserId: currentUserId,
      targetUserId: targetUserId,
      isMyself: isMyself
    });

    // 🔥 使用真实API加载用户信息
    this.loadUserInfo(targetUserId, isMyself);
    
    // 🎯 初始化权限系统（模仿Flutter项目）
    if (currentUser && currentUser.userPoints) {
      permission.accordingToUserPointsForPermission(currentUser.userPoints);
      console.log('✅ 权限系统初始化完成，用户积分:', currentUser.userPoints);
    }
  },

  onShow() {
    // 🔔 自动初始化通知组件
    const app = getApp();
    app.autoInitNotification();
  },

  // 🔥 修改：使用真实API加载用户信息
  loadUserInfo(userId, isMyself) {
    console.log('📡 =============== 加载用户信息 ===============');
    console.log('👤 用户ID:', userId);
    console.log('🔍 是否查看自己:', isMyself);
    
    if (isMyself) {
      // 查看自己的信息 - 调用getUserContent接口
      this.loadMyUserInfo(userId);
    } else {
      // 查看他人的信息 - 调用getUserFilteredContent接口
      this.loadOtherUserInfo(userId);
    }
  },

  // 🔥 新增：加载自己的用户信息和活动
  loadMyUserInfo(userId) {
    console.log('📱 加载自己的用户信息...');
    wx.showLoading({ title: '加载中...', mask: true });
    
    // 🔥 调用getUserContent接口（查询最近365天的数据）
    api.getUserContent(userId, 365)
      .then(res => {
        console.log('✅ getUserContent响应:', res);
        
        if (res.status === 'success') {
          // 使用本地存储的用户基本信息
          const currentUser = storage.getUserInfo();
          if (currentUser) {
            this.displayUserInfo(currentUser);
          }
          
          // 🔥 显示活动列表（只显示进行中的活动）
          if (res.activities && Array.isArray(res.activities)) {
            const ongoingActivities = res.activities.filter(
              activity => activity.activityStatus && Array.isArray(activity.activityStatus) && activity.activityStatus.includes('进行中')
            );
            
            console.log('📊 活动数据筛选:');
            console.log('  总活动数:', res.activities.length);
            console.log('  进行中的活动:', ongoingActivities.length);
            
            this.displayActivities(ongoingActivities);
          } else {
            console.log('⚠️ 没有活动数据');
            this.setData({ activities: [] });
          }
        } else {
          console.error('❌ 获取用户内容失败:', res.message);
          wx.showToast({ title: res.message || '加载失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.error('💥 getUserContent异常:', err);
        wx.showToast({ title: '加载失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
        this.setData({ loading: false });
      });
  },

  // 🔥 新增：加载他人的用户信息和活动
  loadOtherUserInfo(userId) {
    console.log('👥 加载他人的用户信息...');
    wx.showLoading({ title: '加载中...', mask: true });
    
    // 🔥 调用getUserFilteredContent接口
    api.getUserFilteredContent(userId, 'activities')
      .then(res => {
        console.log('✅ getUserFilteredContent响应:', res);
        
        if (res.status === 'success' && res.user) {
          // 🔥 显示他人的用户信息
          const userData = {
            userid: res.user.userid,
            username: res.user.username,
            userPhone: res.user.userPhone || '',  // 🔥 保存手机号（融云用户ID）
            userAvatarUrl: res.user.userAvatarUrl,
            userImgUrls: res.user.userImgUrls,
            userPoints: res.user.userPoints,
            userLikes: res.user.userLikes,
            userFollowers: res.friend_count || 0,  // 🔥 使用friend_count作为粉丝数
            userSignature: res.user.userSignature,
            userHobbies: res.user.userHobbies,
            userFrequentPlaces: res.user.userFrequentPlaces
          };
          
          this.displayUserInfo(userData);
          
          // 🔥 显示活动列表（只显示进行中的活动）
          if (res.activities && Array.isArray(res.activities)) {
            const ongoingActivities = res.activities.filter(
              activity => activity.activityStatus && Array.isArray(activity.activityStatus) && activity.activityStatus.includes('进行中')
            );
            
            console.log('📊 活动数据筛选:');
            console.log('  总活动数:', res.activities.length);
            console.log('  进行中的活动:', ongoingActivities.length);
            
            this.displayActivities(ongoingActivities);
          } else {
            console.log('⚠️ 没有活动数据');
            this.setData({ activities: [] });
          }
        } else {
          console.error('❌ 获取用户过滤内容失败:', res.message);
          wx.showToast({ title: res.message || '加载失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.error('💥 getUserFilteredContent异常:', err);
        wx.showToast({ title: '加载失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
        this.setData({ loading: false });
      });
  },

  // 显示用户信息
  displayUserInfo(userData) {
    console.log('📊 =============== 显示用户信息 ===============');
    console.log('📝 用户数据:', userData);

    // 处理用户相册
    let photos = [];
    if (userData.userImgUrls && Array.isArray(userData.userImgUrls)) {
      photos = userData.userImgUrls;
    } else if (userData.userAvatarUrl) {
      photos = [userData.userAvatarUrl];
    }

    // 🔥 处理爱好标签 - 固定的所有选项
    const allHobbies = ['吃', '喝', '玩', '乐', '购'];
    
    // 🔥 用户选择的爱好（红色高亮）
    let selectedHobbiesArray = [];
    if (userData.userHobbies && Array.isArray(userData.userHobbies)) {
      selectedHobbiesArray = userData.userHobbies;
    }
    
    console.log('🎨 所有爱好选项:', allHobbies);
    console.log('❤️ 用户选择的爱好:', selectedHobbiesArray);
    console.log('🔍 selectedHobbiesArray类型:', typeof selectedHobbiesArray, Array.isArray(selectedHobbiesArray));
    console.log('🔍 selectedHobbiesArray内容:', JSON.stringify(selectedHobbiesArray));

    // 🔥 转换为带选中状态的对象数组，方便WXML判断
    const hobbiesWithStatus = allHobbies.map(hobby => {
      const isSelected = selectedHobbiesArray.includes(hobby);
      console.log(`  爱好"${hobby}": ${isSelected ? '✅选中' : '❌未选中'}`);
      return {
        name: hobby,
        isSelected: isSelected
      };
    });
    
    console.log('🎯 爱好标签处理结果:', hobbiesWithStatus);

    // 🎯 使用等级工具类计算等级名称
    const points = userData.userPoints || 0;
    const levelName = level.getLevelNameFromPoints(points);

    // 格式化数字
    const fans = this.formatNumber(userData.userFollowers || 0);
    const likes = this.formatNumber(userData.userLikes || 0);

    console.log('📊 格式化后的数据:');
    console.log('  🏆 等级名称:', levelName);
    console.log('  👥 粉丝数:', fans);
    console.log('  ❤️ 点赞数:', likes);

    // 🔥 使用图片工具类处理头像和照片（自动HTTP转HTTPS，真机要求）
    const avatar = imageUtil.processAvatar(userData.userAvatarUrl);
    const photosHttps = imageUtil.processUserPhotos(photos, userData.userAvatarUrl);
    
    this.setData({
      userInfo: {
        nickname: userData.username || '用户',
        avatar: avatar,
        photos: photosHttps,
        currentPhotoIndex: 0,
        levelName: levelName,
        fans: fans,
        likes: likes,
        signature: userData.userSignature || '这个人很懒，什么都没留下',
        hobbies: hobbiesWithStatus, // 🔥 使用带选中状态的对象数组
        frequentPlaces: userData.userFrequentPlaces || '未知',
        userId: userData.userid, // 🔥 保存用户ID用于好友关系检查
        userPhone: userData.userPhone || ''  // 🔥 保存手机号（融云用户ID）用于聊天
      },
      loading: false
    });
    
    console.log('✅ 用户信息显示完成');
  },

  // 🔥 新增：显示活动列表
  displayActivities(activities) {
    console.log('📋 =============== 显示活动列表 ===============');
    console.log('📊 活动数量:', activities.length);
    
    const formattedActivities = activities.map((activity, index) => {
      console.log(`  活动${index + 1}:`, activity.activityTitle);
      console.log(`    时间:`, activity.activityPublishTime);
      console.log(`    状态:`, activity.activityStatus);
      
      return {
        id: activity.activityId,
        time: this.formatActivityTime(activity.activityPublishTime),
        title: activity.activityTitle,
        canJoin: !this.data.isMyself, // 不能加入自己的活动
        rawData: activity // 保存原始数据用于申请加入
      };
    });
    
    this.setData({
      activities: formattedActivities
    });
    
    console.log('✅ 活动列表显示完成');
  },

  // 🔥 新增：格式化活动时间
  formatActivityTime(publishTime) {
    try {
      // 解析ISO格式时间: 2025-08-15T10:00:00
      const date = new Date(publishTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (e) {
      console.error('⚠️ 时间格式化失败:', e);
      return publishTime; // 返回原始时间
    }
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 图片切换
  onPhotoChange(e) {
    this.setData({
      'userInfo.currentPhotoIndex': e.detail.current
    });
  },

  // 🔥 修改：申请加入活动
  onJoinActivity(e) {
    const { index } = e.currentTarget.dataset;
    const activity = this.data.activities[index];
    
    console.log('🎯 =============== 用户点击加入活动 ===============');
    console.log('📝 活动索引:', index);
    console.log('📊 活动数据:', activity);
    
    if (!activity || !activity.rawData) {
      wx.showToast({ title: '活动数据错误', icon: 'none' });
      return;
    }
    
    const activityId = activity.rawData.activityId;
    const activityTitle = activity.rawData.activityTitle;
    
    wx.showModal({
      title: '申请加入活动',
      content: `确定要申请加入活动"${activityTitle}"吗？`,
      confirmText: '确定申请',
      confirmColor: '#D84545',
      success: (res) => {
        if (res.confirm) {
          this.submitJoinActivity(activityId, activityTitle);
        }
      }
    });
  },

  // 🔥 新增：提交申请加入活动
  submitJoinActivity(activityId, activityTitle) {
    console.log('📤 =============== 提交申请加入活动 ===============');
    console.log('🎯 活动ID:', activityId);
    console.log('📝 活动标题:', activityTitle);
    
    const currentUser = storage.getUserInfo();
    if (!currentUser) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    
    console.log('👤 当前用户ID:', currentUser.userid);
    console.log('👤 当前用户名:', currentUser.username);
    
    wx.showLoading({ title: '申请中...', mask: true });
    
    // 🔥 调用joinActivity接口
    api.joinActivity(activityId, currentUser.userid, '待审核')
      .then(res => {
        console.log('✅ joinActivity响应:', res);
        
        if (res.status === 'success') {
          wx.showToast({
            title: res.message || '申请成功',
            icon: 'success',
            duration: 2000
          });
        } else {
          // 处理特殊情况（如重复参加）
          if (res.message && (res.message.includes('重复') || res.message.includes('已参加'))) {
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 2000
            });
          } else {
            wx.showToast({
              title: res.message || '申请失败',
              icon: 'none',
              duration: 2000
            });
          }
        }
      })
      .catch(err => {
        console.error('💥 joinActivity异常:', err);
        
        // 🔥 优化错误提示：判断是否是"已参加"的错误
        const errorMsg = err.message || err.msg || err.errMsg || '';
        
        if (errorMsg.includes('已参加') || errorMsg.includes('重复参加')) {
          wx.showModal({
            title: '提示',
            content: '您已经申请加入过这个活动了，请耐心等待发布者审核',
            showCancel: false,
            confirmText: '知道了',
            confirmColor: '#D84545'
          });
        } else {
          wx.showToast({ 
            title: errorMsg || '申请失败，请稍后重试', 
            icon: 'none',
            duration: 2000
          });
        }
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  /**
   * 🔥 跳转到历史记录页面
   */
  goToHistory() {
    console.log('📋 =============== 跳转历史记录页面 ===============');
    
    const targetUserId = this.data.targetUserId;
    const userName = this.data.userInfo.nickname;
    
    console.log('👤 目标用户ID:', targetUserId);
    console.log('👤 用户名:', userName);
    
    if (!targetUserId) {
      wx.showToast({
        title: '用户信息不完整',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/history/index?userId=${targetUserId}&userName=${encodeURIComponent(userName)}`
    });
  }
});
